import { baseUrl } from './env';

export default async(type = 'Get', url = '', data = {}, method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type = "GET") {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }

        if (window.fetch && method == 'fetch') {
            let requsestConfig = {
                credentials: 'include',
                method: type,
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                mode: "cors",
                cache: "force-cache"
            }

            if (type === 'POST') {
                Object.defineProperty(requestConfig, 'body', {
                    value: JSON.stringify(data)
                })
            }

            try {
                var response = await fetch(url, requsestConfig);
                var responseJson = await response.json();
            } catch (error) {
                console.log("------------------Error----------------------------")
                console.log(error)
                console.log("------------------Fetch----------------------------")
                console.log("------------------ErrorEnd-------------------------")
                    //throw new Error(error);
                return [];

            }
            return responseJson;
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }
            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
};